package com.xliang.spider.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author xiongl
 * @create 2016-05-18 17:00
 */
public class HttpUtil
{
    private static Logger logger = Logger.getLogger(HttpUtil.class);
    
    /**
     * 获取客户端ip地址
     * @return
     */
    /*public static String getRemoteIpAddr(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.length() > 15)
        {
            if (ip.indexOf(",") > 0)
            {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }*/
    
    public static boolean downLoadRemoteFile(String url, String filePath, String fileName)
    {
        boolean isSuccess = false;
        InputStream ins = null;
        FileOutputStream fos = null;
        HttpClient client = null;
        try
        {
            client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            if (response == null)
            {
                System.err.println("文件下载失败");
                return isSuccess;
            }
            
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                File file = new File(filePath + "\\" + fileName);
                ins = entity.getContent();
                fos = new FileOutputStream(file);
                /*int len = -1;
                byte[] temp = new byte[1024];
                while ((len = ins.read(temp)) != -1)
                {
                    fos.write(temp, 0, len);
                }
                fos.flush();*/
                IOUtils.copy(ins, fos);
                fos.flush();
                isSuccess = true;
            }
            else
            {
                System.err.println("文件下载失败，httpStatusCode=" + response.getStatusLine().getStatusCode());
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (Exception e1)
                {
                    e1.printStackTrace();
                }
            }
            if (ins != null)
            {
                try
                {
                    ins.close();
                }
                catch (Exception e1)
                {
                    e1.printStackTrace();
                }
            }
        }
        return isSuccess;
    }
    
    public static JSONObject downLoadRemoteFile(String url, String fileName)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", CommonEnum.COMMON_IS.YES.getValue());
        InputStream ins = null;
        FileOutputStream fos = null;
        HttpClient client;
        try
        {
            client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                File file = new File(fileName);
                if (!file.exists())
                {
                    ins = entity.getContent();
                    fos = new FileOutputStream(file);
                    /*int len = 0;
                    byte[] temp = new byte[1024];
                    while ((len = ins.read(temp)) != -1)
                    {
                    fos.write(temp, 0, len);
                    }*/
                    IOUtils.copy(ins, fos);
                    fos.flush();
                    ins.close();
                    fos.close();
                }
                else
                {
                    logger.info("文件：" + fileName + " 已经存在，跳过。。。");
                }
                jsonObject.put("message", "下载成功");
            }
            else
            {
                jsonObject.put("status", CommonEnum.COMMON_IS.NO.getValue());
                jsonObject.put("message", "文件下载失败，rspCode=" + response.getStatusLine().getStatusCode());
            }
        }
        catch (Exception e)
        {
            logger.error("下载文件出现异常", e);
            jsonObject.put("status", CommonEnum.COMMON_IS.NO.getValue());
            jsonObject.put("message", e.getMessage());
        }
        finally
        {
            if (fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (Exception e1)
                {
                    e1.printStackTrace();
                }
            }
            if (ins != null)
            {
                try
                {
                    ins.close();
                }
                catch (Exception e1)
                {
                    e1.printStackTrace();
                }
            }
            
        }
        return jsonObject;
    }
    
    public static String httpGet(String url, Map<String, String> parameter)
    {
        try
        {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url + "?" + buildRequestParameter(parameter));
            HttpResponse response = client.execute(request);
            if (response == null)
            {
                return null;
            }
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                return EntityUtils.toString(response.getEntity());
            }
            return null;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
    
    public static JSONObject httpPost(String url, Map<String, String> param)
    {
        JSONObject jsonObject = null;
        try
        {
            HttpClient client = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost(url);
            if (param != null)
            {
                request.setEntity(new UrlEncodedFormEntity(buildRequestParameterForPost(param)));
            }
            HttpResponse response = client.execute(request);
            if (response == null)
            {
                return jsonObject;
            }
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            }
            return jsonObject;
            
        }
        catch (Exception e)
        {
        
        }
        return jsonObject;
    }
    
    private static List<NameValuePair> buildRequestParameterForPost(Map<String, String> param)
    {
        List<NameValuePair> params = new ArrayList<>();
        if (param != null && !param.isEmpty())
        {
            for (Map.Entry<String, String> entry : param.entrySet())
            {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        return params;
    }
    
    private static String buildRequestParameter(Map<String, String> param)
    {
        if (param == null || param.isEmpty())
        {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : param.entrySet())
        {
            if (sb.length() == 0)
            {
                sb.append(entry.getKey()).append("=").append(entry.getValue());
            }
            else
            {
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
        }
        return sb.toString();
    }
    
    public static JSONObject sendHttpGet(String url, Map<String, String> parameter, Map<String, String> header)
    {
        return null;
    }
    
    public static JSONObject sendHttpPost(String url, Map<String, String> parameter, Map<String, String> header)
    {
        return null;
    }
    
    public static void main(String[] args)
        throws Exception
    {
        //downLoadRemoteFile("http://cv4.jikexueyuan.com/641615eaad5ba6d9043db287241f90a6/201605191016/html5/course_js/01/video/c127b_01_h264_sd_960_540.mp4","E:\\mnt","test2.mp4");
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet requset = new HttpGet("http://ke.jikexueyuan.com/xilie/more");
        HttpResponse response = client.execute(requset);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
        {
            HttpEntity entity = response.getEntity();
            //System.out.println(EntityUtils.toString(entity));
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(entity));
            System.out.println("code:" + jsonObject.get("code"));
            System.out.println("msg:" + jsonObject.get("msg"));
            
            JSONObject data = jsonObject.getJSONObject("data");
            System.out.println("data:" + jsonObject.get("data"));
            System.out.println("is_end:" + data.get("is_end"));
            System.out.println("info:" + data.get("info"));
            
            JSONArray items = data.getJSONArray("info");
            for (int i = 0; i < items.size(); i++)
            {
                Object item = items.get(i);
                System.out.println(item);
            }
            
        }
    }
}
